import api from "../../api/index";

// components/qrCode/qrCode.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: Object,
      value: () => {
        return {};
      },
    },
    show: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {},

  /**
   * 组件的方法列表
   */
  methods: {
    previewImage(){
      wx.previewImage({
        urls: [this.data.data.qrcode]
      })
    },
    onClose() {
      this.triggerEvent("close");
    },
    async saveImageWithAuthCheck() {
      try {
        // 1. 检查权限
        const hasAuth = await this.checkPhotoAlbumAuth();
        if (!hasAuth) {
          // 2. 如果没有权限，引导用户开启
          await this.showAuthModal();
          return;
        }

        // 3. 下载并保存图片
        this.saveNetworkImage();
      } catch (error) {
        wx.showToast({ title: "保存失败", icon: "none" });
      }
    },
    saveNetworkImage() {
      wx.downloadFile({
        url: this.data.data.download, // 网络图片地址
        success: (res) => {
          if (res.statusCode === 200) {
            this.saveImageToPhotosAlbum(res.tempFilePath);
          }
        },
        fail: (err) => {
          wx.showToast({ title: "下载失败", icon: "none" });
        },
      });
    },

    saveImageToPhotosAlbum(filePath) {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          wx.showToast({ title: "保存成功" });
        },
        fail: (err) => {
          if (err.errMsg.includes("auth")) {
            this.showAuthGuide();
          } else {
            wx.showToast({ title: "保存失败", icon: "none" });
          }
        },
      });
    },
    // 显示权限引导弹窗
    showAuthModal() {
      return new Promise((resolve) => {
        wx.showModal({
          title: "权限提示",
          content: "需要您授权保存图片到相册",
          confirmText: "去设置",
          confirmColor: "#73F0EA",
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting["scope.writePhotosAlbum"]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else {
              resolve(false);
            }
          },
        });
      });
    },
    checkPhotoAlbumAuth() {
      return new Promise((resolve) => {
        wx.getSetting({
          success: (res) => {
            const authSetting = res.authSetting;
            if (authSetting["scope.writePhotosAlbum"] === false) {
              resolve(false);
            } else {
              resolve(true);
            }
          },
          fail: () => resolve(false),
        });
      });
    },
  },
});
